import 'dart:async';

import 'package:dmz/base/controller/base_controller.dart';
import 'package:dmz/request/apis.dart';
import 'package:dmz/request/request_client.dart';
import 'package:dmz/routers/routers.dart';
import 'package:dmz/utils/customize_loding.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';

class PassWordPageController extends BaseController {
  TextEditingController photneController = TextEditingController();
  TextEditingController codeController = TextEditingController();

  TextEditingController passwordController = TextEditingController();
  TextEditingController passwordControllerOther = TextEditingController();

  bool isGetCode = true;

  Timer? timer;
  RxInt counter = 60.obs;
  RxInt snedCodeType = 0.obs;

  @override
  void loadNet() {}

  @override
  void onHidden() {}

  @override
  void onInit() {
    super.onInit();
    debugPrint('页面加载2');
  }

  ///下一步跳转
  turnNext() {
    if (isGetCode) {
      Get.toNamed(RouteGet.password,
          preventDuplicates: false, arguments: false); //密码重置页面
    } else {
      //返回登录页
      Get.until((route) => route.settings.name == RouteGet.login);
    }
  }

  void snendChagePasswordCode() {
    if (snedCodeType.value == 1) return;
    if (!loginExamine(codeExamine: true)) return;
    startTimer();
    RequestClient().post(APIS.getCode, data: {'phone': photneController.text},
        onError: (error) {
      if (error.code != 0) {
        EMILoding.hitLoding('发送失败请稍后重试'.tr);
      }
      return false;
    }, onResponse: (p0) {}).then((value) {
      EMILoding.hitLoding('发送成功'.tr, isScuess: true);
    });
  }

  ///验证码 验证
  void checkCode() {
    if (!loginExamine()) return;
    RequestClient().post(APIS.checkCode, data: {
      'phone': photneController.text,
      'code': int.parse(codeController.text),
    }, onError: (error) {
      if (error.code != 0) {
        EMILoding.hitLoding('验证码不正确，请稍后重试'.tr);
      }
      return false;
    }, onResponse: (p0) {}).then((value) {
      turnNext();
    });
  }

  ///设置新密码
  void changePassWord() {
    if (!loginExamine()) return;
    RequestClient().post(APIS.changeCode, data: {
      'phone': photneController.text,
      'password': passwordController.text,
      'code': int.parse(codeController.text),
    }, onError: (error) {
      if (error.code != 0) {
        EMILoding.hitLoding('网络错误请稍后重试'.tr);
      }
      return false;
    }).then((value) {
      EasyLoading.showSuccess('修改成功'.tr);
      turnNext();
    });
  }

  /// 输入框检查  codeExamine 验证码检验（只检验手机号）
  loginExamine({bool codeExamine = false}) {
    if (isGetCode) {
      if (photneController.text.isEmpty && !codeExamine) {
        EMILoding.hitLoding('手机号不能为空'.tr);
        return false;
      }
      if (codeExamine) return true;

      if (codeController.text.isEmpty) {
        EMILoding.hitLoding('验证码不能为空'.tr);
        return false;
      }
      return true;
    }

    if ((passwordController.text.isEmpty ||
            passwordControllerOther.text.isEmpty) &&
        isGetCode) {
      EMILoding.hitLoding('密码不能为空'.tr);
      return false;
    }

    if (passwordController.text != passwordControllerOther.text) {
      EMILoding.hitLoding('两次密码输入不一致，请重新输入'.tr);
      return false;
    }

    return true;
  }

  ///倒计时
  void startTimer() {
    snedCodeType.value = 1;
    const oneSec = Duration(seconds: 1);
    timer = Timer.periodic(
      oneSec,
      (Timer timer) {
        if (counter.value == 0) {
          timer.cancel();
          counter.value = 60;
          snedCodeType.value = 2;
        } else {
          counter.value--;
        }
      },
    );
  }

  @override
  void onClose() {
    timer?.cancel();
    if (isGetCode) {
      // 可选：从 GetX 管理的内存中删除控制器
      Get.delete<PassWordPageController>();
      debugPrint('password ---- 页面销毁00');
    }
    super.onClose();
  }
}

class PassWordBinding extends Bindings {
  @override
  void dependencies() {
    Get.lazyPut(() => PassWordPageController(), fenix: true);
  }
}
